﻿using Learun.Application.Organization;
using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using static Learun.Application.TwoDevelopment.ZZDT_EC.ProjectSugar;
using static Learun.Util.SqlSugar.SqlSugarHelper;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-01-30 15:56
    /// 描 述：图纸目录
    /// </summary>
    public class ec_drawing_catalogueBLL : ec_drawing_catalogueIBLL
    {
        private ec_drawing_catalogueService ec_drawing_catalogueService = new ec_drawing_catalogueService();

        #region 获取数据
        /// <summary>
        /// 获取一个目录下的所有图纸
        /// </summary>
        /// <param name="projId"></param>
        /// <param name="detailId"></param>
        /// <returns></returns>
        public List<string> GetChildNodes(string projId, string folderId)
        {
            var tableName = ProjectSugar.TableName<ec_drawing_catalogueEntity>(projId);
            var dwgtableName = ProjectSugar.TableName<ec_drawing_fileEntity>(projId);
            var allFolder = SqlSugarHelper.Db.Queryable<ec_drawing_catalogueEntity>().AS(tableName).ToList();
            var folder = allFolder.Where(x => x.FullPath.Contains(folderId)).Select(x => x.DrawingCatalogueID);
            var allDwgs = SqlSugarHelper.Db.Queryable<ec_drawing_fileEntity>().AS(dwgtableName)
                .Where(x => folder.Contains(x.DrawingCatalogueID)).Select(x => x.DrawingFileID)
                .ToList();
            return allDwgs;
        }
        /// <summary>
        /// 用于插件端左侧面板里的（按目录）
        /// </summary>
        public List<TreeModel> GetDrawingCategory(string projectId, string onlyFolderFlag)
        {
            List<TreeModel> treeList = new List<TreeModel>();
            try
            {
                //增加权限
                var ec_accessBLL = new ec_accessBLL();
                var ec_drawing_fileBLL = new ec_drawing_fileBLL();
                var accessList = ec_accessBLL.GetList("{ProjectId:\"" + projectId + "\", EntityTableID: \"ec_drawing_file\"}");

                string queryJson = "{\"ProjectId\":\"" + projectId + "\"}";
                var listCatalogue = this.GetList(queryJson);
                var listFile = ec_drawing_fileBLL.GetList("{\"ProjectId\":\"" + projectId + "\", \"IsDelete\": \"0\"}");

                foreach (var itemCatalogue in listCatalogue)
                {
                    // 给lining演示的
                    itemCatalogue.AllowCreatedByCurUser = true;
                    //
                    TreeModel nodeCatalogue = new TreeModel();
                    nodeCatalogue.id = itemCatalogue.DrawingCatalogueID;
                    nodeCatalogue.text = itemCatalogue.DrawingCatalogueName;
                    nodeCatalogue.value = itemCatalogue.DrawingCatalogueID;
                    nodeCatalogue.nodeType = "0";
                    nodeCatalogue.showcheck = false;
                    nodeCatalogue.checkstate = 0;
                    nodeCatalogue.isexpand = false;
                    nodeCatalogue.parentId = itemCatalogue.UpDrawingCatalogueID;
                    nodeCatalogue.NodeExtData = itemCatalogue;
                    treeList.Add(nodeCatalogue);
                    if (!onlyFolderFlag.Equals("1"))
                    {
                        var listFileTmp = listFile.Where(x => x.DrawingCatalogueID == itemCatalogue.DrawingCatalogueID).ToList();
                        if (listFileTmp != null && listFileTmp.Count > 0)
                        {
                            listFileTmp = listFileTmp.OrderBy(x => x.OrderID).ThenBy(x => x.DrawingFileName).ToList();
                            foreach (var itemFile in listFileTmp)
                            {
                                itemFile.AllUsersCanEdit = ec_accessBLL.GetAllUsersCanEditDrawing(projectId, itemFile.DrawingFileID);
                                if (accessList.Any(x => x.EntityID == itemFile.DrawingFileID))
                                {
                                    itemFile.ReadOnlyInCAD = false;
                                }
                                else
                                {
                                    itemFile.ReadOnlyInCAD = false;  //暂时默认都可以，后面在看
                                }
                                TreeModel nodeFile = new TreeModel();
                                nodeFile.id = itemFile.DrawingFileID;
                                nodeFile.text = itemFile.DrawingFileName;
                                nodeFile.value = itemFile.DrawingFileID;
                                nodeFile.nodeType = "1";
                                nodeFile.showcheck = false;
                                nodeFile.checkstate = 0;
                                nodeFile.isexpand = false;
                                nodeFile.parentId = itemCatalogue.DrawingCatalogueID;
                                nodeFile.NodeExtData = itemFile;

                                treeList.Add(nodeFile);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex, ex.Message + "※※※" + ex.StackTrace);
                }
            }

            return treeList.ToTree();
        }

        /// <summary>
        /// 用于插件端左侧面板里的（按图纸类型）
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public List<TreeModel> GetDrawingCategoryByType(string projectId)
        {
            List<TreeModel> treeList = new List<TreeModel>();

            try
            {
                //增加权限
                ec_dataitemIBLL dataItemIBLL = new ec_dataitemBLL();
                var ec_accessBLL = new ec_accessBLL();
                var ec_drawing_fileBLL = new ec_drawing_fileBLL();
                var accessList = ec_accessBLL.GetList("{ProjectId:\"" + projectId + "\", EntityTableID: \"ec_drawing_file\"}");

                string queryJson = "{\"ProjectId\":\"" + projectId + "\"}";
                var listCatalogue = dataItemIBLL.GetDetailList("Be_DrawingType", "", projectId, false); //dataItemIBLL.GetDetailList("Be_DrawingType");

                var listFile = ec_drawing_fileBLL.GetList("{\"ProjectId\":\"" + projectId + "\", \"IsDelete\": \"0\"}");
                foreach (var itemCatalogue in listCatalogue)
                {
                    TreeModel nodeCatalogue = new TreeModel();
                    nodeCatalogue.id = itemCatalogue.DataItemCode; //F_ItemValue;
                    nodeCatalogue.text = itemCatalogue.DataItemName; //F_ItemName;
                    nodeCatalogue.value = itemCatalogue.DataItemCode;  //F_ItemValue;
                    nodeCatalogue.nodeType = "0";
                    nodeCatalogue.showcheck = false;
                    nodeCatalogue.checkstate = 0;
                    nodeCatalogue.isexpand = false;
                    nodeCatalogue.parentId = "0";
                    nodeCatalogue.NodeExtData = itemCatalogue;
                    treeList.Add(nodeCatalogue);

                    var listFileTmp = listFile.Where(x => x.DrawingType == itemCatalogue.DataItemDetailID && x.IsDelete != 1).ToList();
                    foreach (var itemFile in listFileTmp)
                    {
                        itemFile.AllUsersCanEdit = ec_accessBLL.GetAllUsersCanEditDrawing(projectId, itemFile.DrawingFileID);
                        if (accessList.Any(x => x.EntityID == itemFile.DrawingFileID))
                        {
                            itemFile.ReadOnlyInCAD = false;
                        }
                        else
                        {
                            itemFile.ReadOnlyInCAD = false;  //暂时默认都可以，后面在看
                        }
                        TreeModel nodeFile = new TreeModel();
                        nodeFile.id = itemFile.DrawingFileID;
                        nodeFile.text = itemFile.DrawingFileName;
                        nodeFile.value = itemFile.DrawingFileID;
                        nodeFile.nodeType = "1";
                        nodeFile.showcheck = false;
                        nodeFile.checkstate = 0;
                        nodeFile.isexpand = false;
                        nodeFile.parentId = itemCatalogue.DataItemCode;
                        nodeFile.NodeExtData = itemFile;
                        treeList.Add(nodeFile);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex, ex.Message + "※※※" + ex.StackTrace);
                }
            }

            return treeList.ToTree();
        }

        /// <summary>
        /// 用于插件端左侧面板里的（按系统）
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public List<TreeModel> GetDrawingCatalogueBySystem(string projectId)
        {
            List<TreeModel> treeList = new List<TreeModel>();
            try
            {
                //增加权限
                ec_dataitemIBLL dataItemIBLL = new ec_dataitemBLL();
                var ec_accessBLL = new ec_accessBLL();
                var ec_drawing_fileBLL = new ec_drawing_fileBLL();
                var accessList = ec_accessBLL.GetList("{ProjectId:\"" + projectId + "\", EntityTableID: \"ec_drawing_file\"}");

                string queryJson = "{\"ProjectId\":\"" + projectId + "\"}";
                var listCatalogue = dataItemIBLL.GetDetailList("Be_DrawingSystem", "", projectId, false);   //GetDetailList("Be_DrawingSystem");
                var listFile = ec_drawing_fileBLL.GetList("{\"ProjectId\":\"" + projectId + "\", \"IsDelete\": \"0\"}");

                foreach (var itemCatalogue in listCatalogue)
                {

                    TreeModel nodeCatalogue = new TreeModel();
                    nodeCatalogue.id = itemCatalogue.DataItemDetailID; //F_ItemDetailId;
                    nodeCatalogue.text = itemCatalogue.DataItemName + "," + itemCatalogue.DataItemCode; //名字 + 编码 20230512;
                    nodeCatalogue.value = itemCatalogue.DataItemDetailID;  //F_ItemDetailId;
                    nodeCatalogue.nodeType = "0";
                    nodeCatalogue.showcheck = false;
                    nodeCatalogue.checkstate = 0;
                    nodeCatalogue.isexpand = false;
                    nodeCatalogue.parentId = itemCatalogue.UpDataItemDetailID; //F_ParentId;
                    nodeCatalogue.NodeExtData = itemCatalogue;
                    treeList.Add(nodeCatalogue);

                    var listFileTmp = listFile.Where(x => x.DrawingSystem == itemCatalogue.DataItemDetailID && x.IsDelete != 1).ToList();
                    foreach (var itemFile in listFileTmp)
                    {
                        itemFile.AllUsersCanEdit = ec_accessBLL.GetAllUsersCanEditDrawing(projectId, itemFile.DrawingFileID);
                        if (accessList.Any(x => x.EntityID == itemFile.DrawingFileID))
                        {
                            itemFile.ReadOnlyInCAD = false;
                        }
                        else
                        {
                            itemFile.ReadOnlyInCAD = false;  //暂时默认都可以，后面在看
                        }
                        TreeModel nodeFile = new TreeModel();
                        nodeFile.id = itemFile.DrawingFileID;
                        nodeFile.text = itemFile.DrawingFileName;
                        nodeFile.value = itemFile.DrawingFileID;
                        nodeFile.nodeType = "1";
                        nodeFile.showcheck = false;
                        nodeFile.checkstate = 0;
                        nodeFile.isexpand = false;
                        nodeFile.parentId = itemCatalogue.DataItemDetailID;
                        nodeFile.NodeExtData = itemFile;
                        treeList.Add(nodeFile);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex, ex.Message + "※※※" + ex.StackTrace);
                }
            }

            return treeList.ToTree();
        }
        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_drawing_catalogueEntity> GetList(string queryJson, Pagination pagination = null)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                var DrawingCatalogueName = queryParam["DrawingCatalogueName"]?.ToString();
                var FullPathContains = queryParam["FullPathContains"]?.ToString();
                var CurDrawingCatalogueID = queryParam["CurDrawingCatalogueID"]?.ToString();
                var UpDrawingCatalogueID = queryParam["UpDrawingCatalogueID"]?.ToString();
                var EngineDataID = queryParam["EngineDataID"]?.ToString();

                var tableName = TableName<ec_drawing_catalogueEntity>(queryParam["ProjectId"]?.ToString());
                var fileTableName = TableName<ec_drawing_fileEntity>(queryParam["ProjectId"]?.ToString());
                var pixelTableName = TableName<ec_enginedata_pixelEntity>(queryParam["ProjectId"]?.ToString());

                var query = Db.Queryable<ec_drawing_catalogueEntity>().AS(tableName)
                    .WhereIF(!string.IsNullOrEmpty(DrawingCatalogueName), x => x.DrawingCatalogueName.Contains(DrawingCatalogueName))
                    .WhereIF(!string.IsNullOrEmpty(FullPathContains), x => x.FullPath.Contains(FullPathContains))
                    .WhereIF(!string.IsNullOrEmpty(CurDrawingCatalogueID), x => !x.FullPath.Contains(CurDrawingCatalogueID))
                    .WhereIF(!string.IsNullOrEmpty(UpDrawingCatalogueID), x => x.UpDrawingCatalogueID == UpDrawingCatalogueID)
                    .InnerJoinIF<ec_drawing_fileEntity>(!string.IsNullOrEmpty(EngineDataID), (a, b) => a.DrawingCatalogueID == b.DrawingCatalogueID).AS<ec_drawing_fileEntity>(fileTableName)
                    .InnerJoinIF<ec_enginedata_pixelEntity>(!string.IsNullOrEmpty(EngineDataID), (a, b, c) => b.DrawingFileID == c.DrawingFileID
                        && c.EngineDataID == EngineDataID).AS<ec_enginedata_pixelEntity>(pixelTableName)
                    .OrderBy(x => x.OrderID);
                var list = new  List<ec_drawing_catalogueEntity>();
                if (pagination == null)
                {
                    list = query.ToList();
                }
                else
                {
                    list = query.ToPageList(pagination.page, pagination.rows);
                }
                var users = Db.Queryable<UserEntity>().ToList();
                list?.ForEach(x =>
                {
                    x.CreateUserName = users.FirstOrDefault(y => y.F_UserId == x.CreateUserID)?.F_RealName;
                });
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_drawing_catalogueEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                return ec_drawing_catalogueService.GetEntity(keyValue, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            try
            {
                ec_drawing_catalogueService.DeleteEntity(keyValue, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_drawing_catalogueEntity entity, string ProjectId)
        {
            try
            {
                ec_drawing_catalogueService.SaveEntity(keyValue, entity, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 新增
        /// <summary>
        /// <returns></returns>
        public void InertEntity(ec_drawing_catalogueEntity entity, string ProjectId)
        {
            try
            {
                ec_drawing_catalogueService.InertEntity(entity, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 编辑
        /// <summary>
        /// <returns></returns>
        public void EditEntity(ec_drawing_catalogueEntity entity, string ProjectId)
        {
            try
            {
                ec_drawing_catalogueService.EditEntity(entity, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

    }
}
